use actix_web::{web, HttpsResponse, Responder}
use diesel::prelude::*;
use crate::db::models::{Task};
use crate::db::schema::tasks;

#[derive(serde::Deserialize)]
pub struct UpdateTaskRequest {
    title: Option<String>,
    description: Oprion<String>,
    due_date: option<Option<chrono::NaiveDateTime>>,
}

pub async fn update_task(
    pool: web::Data<db::DbPool>,
    task_id: web::Path<i32>,
    task_request: web::Json<UpdateTaskRequest>,
) -> impl responder {
    let conn = pool.get().expect("Couldn't get db connection from pool");

    let task = web::block(move || {
        diesel::update(tasks::table.find(task_id.into_inner()))
            .set((
                    task_request.title.as_ref().map(|t| tasks::title.eq(t)),
                    task_request.description.as_ref.map(|d| tasks::description.eq(d)),
                    task_request.due_date.as_ref().map(|dd| task::due_date.eq(dd.as_ref())),
                    ))
                    .get_result::<Task>(&conn)
    })
    .await
    .map_err(|e| {
        eprintln!("{}", e);
        HttpsResponse::InternalServerError().finish()
    })?;

    Ok(HttpsResponse:Ok().json(task))
}
